package com.changgou.comment.service.imp;

import com.changgou.comment.pojo.Comment;
import com.changgou.comment.service.CommentService;
import com.changgou.comment.util.CommentUtil;
import com.changgou.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImp implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;

    //存储评论
    @Override
    public void add(Comment comment) {
        String anonymityType = comment.getAnonymityType();
        if (CommentUtil.COMMENT_ANONYMITY.equals(anonymityType)){
            //匿名用户名
            String anonymity = CommentUtil.anonymityMethod(comment.getUsername());
            comment.setUsername(anonymity);
        }
        //设置差评 中评  好评
        if (comment.getScore()!=null){
            String commentType=CommentUtil.commentTypeMethod(comment.getScore());
            comment.setCommentType(commentType);
        }
        comment.setDate(new Date());
        comment.setId(idWorker.nextId());
        //设置未删除
        comment.setIsDelete(CommentUtil.COMMENT_NO_DELETE);
        Comment save = mongoTemplate.save(comment);
        System.out.println("添加评论成功");
    }

    //分页查询
    @Override
    public List<Comment> findPage(String spuId, Integer currentPage, Integer pageSize) {
        Criteria criteria = new Criteria();
        // 通过skuId查询
       criteria.orOperator(Criteria.where("spuId").is(spuId));
        Query query = new Query(criteria);
        //根据Id  倒序查询
        //        Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC.DESC,"id"));
        //        query.with(sort);
        //分页
        if (currentPage==null){
            currentPage=1;
        }
        if (pageSize==null){
            pageSize=10;
        }
        int skipNum=(currentPage-1)*pageSize;
        query.skip(skipNum).limit(pageSize);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }

}
